<?php
/**
 * Here is your custom functions.
 */


/**
 * 获取ai指令
 * @param null $key
 * @return array|mixed|null
 */
function getAiCommand($key=null)
{
    $dataMap = \app\model\ai\AiCommandModel::getInstance()->getWhere(['isdel'=>0])->orderBy('id','desc')->pluck('command','key')->toArray();
    if($key){
        if(isset($dataMap[$key])){
            return $dataMap[$key];
        }else{
            return config('param.'.$key,'');
        }
    }

    return $dataMap;
}

/**
 * 段落分析
 * @param $parts
 * @return array
 */
function partsAnalyze($parts)
{
    $subTitles = [];
    foreach ($parts as $k=>&$val) {
        //如果没有中文,则过滤掉该片段
        $pattern = '/[\x{4e00}-\x{9fa5}]+/u';
        $res = preg_match_all($pattern, $val, $matches);
        if($res==false){
            unset($parts[$k]);
            continue;
        }

        $replaceStr =  ['`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>','·','+','-','_',
                        '《','》','/','￥','……','（','）','―','【','】','‘','”', '“','"','\'','’',' ','「','」'];
        $val = str_replace($replaceStr,"",$val);
        $val = preg_replace('/^\d+[\.]+/','',$val);
        if($val==false){
            unset($parts[$k]);
            continue;
        }

        $replaceStr =  ['`','~','!','@','#','$','^','&','*','(',')','=','|','{','}','\\',':',';',',','[',']','.','+','-','_',
                        '<','>','《','》','/','?','！','￥','……','（','）','―','|','【','】',
                        '‘','；','：','”','“','。','，','、','？',', ','\'','"','’',' '];
        $subTitle = str_replace($replaceStr, "\n",$val);
        $subTitles[] = array_values(array_filter(explode("\n", $subTitle)));
    }

    return [$parts,$subTitles];
}

/**
 * 获取佣金比例
 * @param $userSn
 * @return array
 */
function getcommissionRate($userSn)
{
    $commissionPlan = \app\model\user\UserCommissionPlanModel::getInstance()->getWhere(['user_sn'=>$userSn])->value('commission_plan');
    $commissionPlan = $commissionPlan ? json_decode($commissionPlan, true) : [];
    $defaultCommission = \app\common\lib\Constant::COMMISSION_RATE;
    $commissionRate = [];

    if($commissionPlan){
        $commissionRateMap = array_column($commissionPlan,null,'promotion_project');
        foreach ($defaultCommission as $default){
            if(isset($commissionRateMap[$default['promotion_project']])==false){
                $commissionRate[] = $default;
            }else{
                $commissionRate[] = $commissionRateMap[$default['promotion_project']];
            }
        }
    }else{
        $commissionRate = $defaultCommission;
    }

    return array_column($commissionRate,null,'promotion_project');
}

/**
 * 获取素材
 * @param $materialIds
 * @return array
 */
function getMaterialData($materialIds)
{
    if(empty($materialIds)){
        return [];
    }
    $materialIds = is_string($materialIds) ? explode(',',$materialIds):$materialIds;
    $materialData = \app\model\material\MaterialDataModel::getInstance()->getWhere([['id','in',$materialIds]])->get();
    $heighData = [];
    $normalData = [];
    foreach ($materialData as $material){
        $videoData = $material['heigh_video_data'] ? json_decode($material['heigh_video_data'], true):[];
        if($videoData){
            foreach ($videoData as $video){
                $heighData[] = [
                    'tts'=>$video['tts'],
                    'height'=>$video['height'],
                    'width'=>$video['width'],
                    'video'=>$video['video'],
                    'video_scale'=>$video['video_scale']??'',
                ];
            }
        }

        $videoData2 = $material['normal_video_data'] ? json_decode($material['normal_video_data'], true):[];
        if($videoData2){
            foreach ($videoData2 as $video){
                $normalData[] = [
                    'tts'=>$video['tts'],
                    'height'=>$video['height'],
                    'width'=>$video['width'],
                    'video'=>$video['video'],
                    'video_scale'=>$video['video_scale']??'',
                ];
            }
        }
    }

    return ['heigh'=>$heighData,'normal'=>$normalData];
}

/**
 * 语音合成
 * @param $text
 * @param $option
 * @return array
 * @throws Throwable
 * @throws \app\exception\IndexException
 */
function timbreTextToVoice($text,$option)
{
    if($text==false){
        throw new \app\exception\IndexException(4020,'文本不能为空');
    }

    if(strpos($option['speaker'],'streaming')!==false){
        $option = [
            'speaker'=>$option['speaker'],
            'speed'=>floatval(($option['speed']??'1.0')),
            'volume'=>floatval(($option['volume']??'1.0')),
            'audio_type'=>$option['audio_type']??'mp3',
        ];
        $result = \app\common\lib\VolcanoTts::getInstance()->textToVoice($text,$option);
    }else{
        $option = [
            'speaker'=>$option['speaker'],
            'speed'=>(string)($option['speed']??'1.0'),
            'volume'=>(string)($option['volume']??'50'),
            'audio_type'=>$option['audio_type']??'mp3',
        ];
        $result = \app\common\lib\MoyinTts::getInstance()->textToVoice($text,$option);
    }

    $mp3FileName = runtime_path('timbre_'.$option['speaker'].'.mp3');
    file_put_contents($mp3FileName,$result['content']);

    $res = \app\common\lib\TencentCos::getInstance()->uploadLocalFile($mp3FileName,'timbre_mp3_example');
    $voiceUrl = 'https://'.$res['Location'];
    @unlink($mp3FileName);

   return ['voice_url'=>$voiceUrl,'srt_address_data'=>$result['srt_address_data']];
}